#!/bin/bash

# Container run script for OA Exam System
# Author: Alex
# Version: 1.0

set -e

# Configuration
IMAGE_NAME="kstephenlgz/oa-exam:latest"
CONTAINER_NAME="oa-exam-container"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Function to check if container exists
container_exists() {
    docker ps -a --format '{{.Names}}' | grep -q "^${CONTAINER_NAME}$"
}

# Function to check if container is running
container_running() {
    docker ps --format '{{.Names}}' | grep -q "^${CONTAINER_NAME}$"
}

# Function to stop and remove existing container
cleanup_container() {
    if container_exists; then
        print_status "Stopping and removing existing container..."
        if container_running; then
            docker stop "${CONTAINER_NAME}"
        fi
        docker rm "${CONTAINER_NAME}"
        print_success "Container cleaned up"
    fi
}

# Function to run the container
run_container() {
    print_status "Starting container: ${CONTAINER_NAME}"

    # Create logs directory if it doesn't exist
    mkdir -p ./logs

    # Run container with optimized settings for the network environment
    docker run -d \
        --name "${CONTAINER_NAME}" \
        --network host \
        --restart unless-stopped \
        --env-file .env \
        --env CONTAINER=true \
        --volume "$(pwd)/logs:/app/logs" \
        --volume /tmp/.X11-unix:/tmp/.X11-unix:rw \
        --shm-size=2gb \
        --memory=4gb \
        --cpus=2 \
        --security-opt seccomp=unconfined \
        --cap-add=SYS_ADMIN \
        "${IMAGE_NAME}"

    if [[ $? -eq 0 ]]; then
        print_success "Container started successfully"
        print_status "Container ID: $(docker ps -q -f name=${CONTAINER_NAME})"
    else
        print_error "Failed to start container"
        exit 1
    fi
}

# Function to show container status
show_status() {
    print_status "Container status:"
    docker ps -f name="${CONTAINER_NAME}" --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"

    echo ""
    print_status "Recent logs:"
    docker logs --tail 20 "${CONTAINER_NAME}"
}

# Function to show usage
show_usage() {
    echo "Usage: $0 [OPTION]"
    echo "Options:"
    echo "  start     Start the container (default)"
    echo "  stop      Stop the container"
    echo "  restart   Restart the container"
    echo "  logs      Show container logs"
    echo "  status    Show container status"
    echo "  shell     Open shell in container"
    echo "  clean     Stop and remove container"
    echo "  help      Show this help message"
}

# Main function
main() {
    case "${1:-start}" in
        "start")
            cleanup_container
            run_container
            show_status
            ;;
        "stop")
            if container_running; then
                docker stop "${CONTAINER_NAME}"
                print_success "Container stopped"
            else
                print_warning "Container is not running"
            fi
            ;;
        "restart")
            if container_exists; then
                docker restart "${CONTAINER_NAME}"
                print_success "Container restarted"
                show_status
            else
                print_error "Container does not exist"
                exit 1
            fi
            ;;
        "logs")
            if container_exists; then
                docker logs -f "${CONTAINER_NAME}"
            else
                print_error "Container does not exist"
                exit 1
            fi
            ;;
        "status")
            show_status
            ;;
        "shell")
            if container_running; then
                docker exec -it "${CONTAINER_NAME}" /bin/bash
            else
                print_error "Container is not running"
                exit 1
            fi
            ;;
        "clean")
            cleanup_container
            ;;
        "help"|"-h"|"--help")
            show_usage
            ;;
        *)
            print_error "Unknown option: $1"
            show_usage
            exit 1
            ;;
    esac
}

# Check if Docker is running
if ! docker info >/dev/null 2>&1; then
    print_error "Docker is not running. Please start Docker and try again."
    exit 1
fi

# Run main function
main "$@"